<?php

namespace app\communal\controller;

use app\Api;
use think\Exception;
use app\logic\WeChat as LogicWeChat;
use app\logic\AliPay as LogicAliPay;
use app\model\ApplyForSettled as ModelApplyForSettled;
use think\Request;

class Notify extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信公众号支付回调地址 \n
     * URI : /notify.wechat.public.pay
     * @param :
     *  name   |  type  | null | description
     * --------|--------|------|-------------
     * --------| ------ | ---- | 无
     *
     * @return
     *  name   |  type  | description
     * --------|--------|-------------
     * --------| ------ |  无
     *
     */
    public function weChatPublicNumberPay()
    {
        try {
            $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : [];
            if ($postStr === []) exit('error');

            $arr_param = $this->xmlToArray($postStr);
            if (isset($arr_param['sign'])) {
                $wechat_sign = $arr_param['sign'];
            } else {
                exit('error');
            }
            unset($arr_param['sign']);
            $res_sign = LogicWeChat::getInstance()->weChatSign($arr_param, config('wechat.public_number_pay_key'));
            $sign = $res_sign['sign'];
            if ($wechat_sign == $sign) {
                if ($arr_param['result_code'] == 'SUCCESS') {
                    // 业务处理
                    echo 'OK';
                }
                exit('success');
            }

            exit('error');
        } catch (Exception $e) {
            exit('error');
        }
    }

    /**
     * 支付宝APP支付回调地址 \n
     * URI : /mobile/notify.ali.app.pay
     * @param :
     *  name   |  type  | null | description
     * --------|--------|------|-------------
     * --------| ------ | ---- | 无
     *
     * @return
     *  name   |  type  | description
     * --------|--------|-------------
     * --------| ------ |  无
     *
     */
    public function aliAppPay()
    {
//        $this->requestLogger('1---------  ' . Request::instance()->param());
        $arr_param = Request::instance()->except('sign,sign_type');
        $str_sign = Request::instance()->param('sign', '');
        //获取module
        if (isset($arr_param['passback_params'])){
            $module = urldecode($arr_param['passback_params']);
        }else{
            exit('error');
        }
        //验证签名是否正确
        $res = LogicAliPay::getInstance()->verify(LogicAliPay::getInstance()->getSignContent($arr_param), $str_sign, $module);
        if ($res === true) {
            if (isset($arr_param['trade_status']) && $arr_param['trade_status'] == 'TRADE_SUCCESS') {
//                $this->requestLogger('2---------  ' . Request::instance()->param());
                // 业务处理
                if ($module == 'courier' || $module == 'driver'){
                    ModelApplyForSettled::getInstance()->payNotifySet($arr_param['out_trade_no'],2);
                }elseif ($module == 'user'){
                    ModelApplyForSettled::getInstance()->userOrderNotifySet($arr_param['trade_no'],$arr_param['out_trade_no'],2);
                }else{
                    exit('error');
                }
                echo 'OK';
            }
            exit('success'); //表示已经成功接收回调信息了
        } else {
            exit('error');
        }
    }

    /**
     * 微信APP支付回调地址 \n
     * URI : /mobile/notify.wechat.app.pay
     * @param :
     *  name   |  type  | null | description
     * --------|--------|------|-------------
     * --------| ------ | ---- | 无
     *
     * @return
     *  name   |  type  | description
     * --------|--------|-------------
     * --------| ------ |  无
     *
     */
    public function weChatAppPay()
    {
        $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : [];
        if ($postStr === []) {
            exit('error');
        }
        $param = $this->xmlToArray($postStr);
        if (isset($param['sign'])) {
            $wechat_sign = $param['sign'];
        } else {
            exit('error');
        }
        unset($param['sign']);
        $arr_sign = LogicWeChat::getInstance()->weChatSign($param, config('wechat.app_pay_key'));
        $str_sign = $arr_sign['sign'];
        if ($wechat_sign == $str_sign) {
            if ($param['result_code'] == 'SUCCESS') {
                // 业务处理
                echo 'OK';
            }
            exit('success');
        } else {
            exit('error');
        }
    }

    /**
     * 请求日志生成日志
     * @access public
     * @param string $log_content 日志内容
     * @since 1.0
     */
    private function requestLogger($log_content)
    {
        $log_filename = "log_request_" . date('Ymd') . ".xml";
        file_put_contents($log_filename, date('Y-m-d H:i:s') . "----" . $log_content . "\r\n\r\n", FILE_APPEND);
    }
}
